package com.sudichina.sudichina.view.activity.dentification;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sudichina.sudichina.MyApp;
import com.sudichina.sudichina.NET.Api;
import com.sudichina.sudichina.NET.NetUtils;
import com.sudichina.sudichina.NET.onRequestDataFinish;
import com.sudichina.sudichina.R;
import com.sudichina.sudichina.bean.Result;
import com.sudichina.sudichina.bean.User;
import com.sudichina.sudichina.utils.DialogFrameAnimUtils;
import com.sudichina.sudichina.utils.Toastutils;
import com.sudichina.sudichina.view.activity.main.BaseActivity;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ${杨伟乔} on 2017/3/6.
 * 邮箱: yangweiqiao@126.com
 * QQ: 463217558
 * 别人光鲜的背后或者有着太多不为人知的痛苦
 * 学习可以改变一切、 行动可以解决一切问题、
 */
public class IdentificationActivity extends BaseActivity implements onRequestDataFinish {

    @BindView(R.id.identification_title)
    TextView privateIdentificationTitle;
    @BindView(R.id.identification_left)
    ImageView privateIdentificationLeft;
    @BindView(R.id.toolbar)
    Toolbar privateToolbar;
    @BindView(R.id.et_real_name)
    EditText privateEtRealName;
    @BindView(R.id.textView2)
    TextView privateTextView2;
    @BindView(R.id.et_id_no)
    EditText privateEtIdNo;
    @BindView(R.id.iv_id)
    ImageView privateIvId;
    @BindView(R.id.tijiao)
    Button privateTijiao;
    private static final int MY_PERMISSIONS_REQUEST_CAMRE = 1000;
    private static final int MY_PERMISSIONS_REQUEST_PHOTO = 999;

    Bitmap bm;
    String drivingLicensePath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_identification);
        ButterKnife.bind(this);

        initView();


    }




    private void initView() {

          /*
        标题栏
         */
        //找到控件
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        TextView toolbar_title = (TextView) findViewById(R.id.identification_title);
        toolbar.setTitle("");
        //设置标题
        toolbar_title.setText("身份认证中心");
        //设置支持actionbar
        setSupportActionBar(toolbar);

    }

    @OnClick({R.id.identification_left, R.id.et_real_name, R.id.et_id_no, R.id.iv_id, R.id.tijiao})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.identification_left:
                finish();
                break;

            case R.id.iv_id:
                //点击选择图片
                makePhoto();

                break;
            case R.id.tijiao:

                //点击提交信息
                //获取用户的填写的信息
                String name = privateEtRealName.getText().toString().trim();
                String idNO = privateEtIdNo.getText().toString().trim();


                if (name == null) {

                    Toastutils.showToast("请填写姓名");
                    return;
                }
                if (idNO == null) {

                    Toastutils.showToast("请输入证件号码");
                    return;
                }
                if (bm == null) {
                    Toastutils.showToast("请上传证件照片");
                    return;
                }
//所有的信息都填写正确后 提交

// TODO: 2017/3/7 接口调试


//final String url, final Map<String, String> map, Map<String, String> files, final onRequestDataFinish listener
                Map<String, Object> map = new HashMap<>();
/**
 * id :Long 车主Id （信息修改时使用）
 accountName; Long 用户
 realName：String 真实姓名
 drivingLicense：String 驾照号码
 drivingLicensePath：驾照图片
 data.put("accountId", id);
 data.put("accountName", accountName);
 data.put("realName", realName);
 data.put("drivingLicense", drivingLicense);
 */
                map.put("accountId", String.valueOf(MyApp.getCurrentUser().getId()));


                map.put("accountName", (MyApp.getCurrentUser().getAccountName()));
                map.put("realName", name);
                map.put("drivingLicense", idNO);
                HashMap<String, String> hashMap = new HashMap<>();

                hashMap.put("drivingLicensePath", drivingLicensePath);


                NetUtils.formPost(Api.SUBMIT, map, hashMap, null, this);

                DialogFrameAnimUtils.startSucessAnim(this, this, "身份信息提交成功");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //跳转到车辆认证中心
                        startActivity(new Intent(IdentificationActivity.this, CarIdentificationActivity.class));
                        finish();
                    }
                }, 2000);


                break;
        }
    }

    private void makePhoto() {


        Intent intent;


        intent = new Intent();
                    /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
                    /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT);
                    /* 取得相片后返回本画面 需要带回数据  所以开启  */
        startActivityForResult(intent, MY_PERMISSIONS_REQUEST_PHOTO);


    }

    @Override
    public void requestdataFinish(String catalog, Object bean) {

        switch (catalog) {
            case Api.LOADCAROWNERBYACCOUNTID:
                Result<User> result = (Result<User>) bean;
                int code = result.getCode();

                if (code == 1) {
                    //获取成功
                    User data = result.getData();
                    /**
                     * "msg": "成功！",
                     "data":
                     {
                     "id": 25,
                     "status": null,
                     "gmtCreate": 1473210778000,
                     "gmtModified": 1473210778000,
                     "realName": "武小鹏",
                     "accountId": 37,
                     "drivingLicense": "585214758525369855",
                     "drivingLicensePath": "http://192.168.1.35:8080/sudichina/upload//2016//09//07//eec56ab9-5d6b-49bf-bbda-6da170db5e70.jpg",
                     "accountProxyId": null,
                     "auditStatus": null,
                     "createDate": null,
                     "recordSource": null,
                     "proxyType": null,
                     "dataStatus": null
                     },
                     "code": 1,
                     "success": true

                     */
                    String auditStatus = data.getAuditStatus();


                    if (auditStatus == null) {
                        //没有认证
                        //显示认证的界面
//                        Toastutils.showToast("进行认证");

                    } else if (auditStatus.equals("1")) {
                        //认证过
                        //显示信息的界面
//                        Toastutils.showToast("认证通过");
//                        startActivity(new Intent(this,CarDetailActivity.class));
                        DialogFrameAnimUtils.startSucessAnim(this, this, "认证成功,无须再次认证");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 2000);


                    }

                } else {
                    //失败
                    Toastutils.showToast(result.getMsg());
                }


                break;
            case Api.SUBMIT:
                String bean1 = (String) bean;
                System.out.println("证件信息:" + (String) bean);


                break;

        }

    }

    @Override
    public void requestdataFailed(IOException e) {

    }


    /**
     * 点击的相册和照相界面返回的数据
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (requestCode) {

                case MY_PERMISSIONS_REQUEST_PHOTO:  //相册选择头像
                    try {
                        /**
                         * 把图片传递到到界面
                         */
                        Uri originalUri = data.getData();
                        bm = MediaStore.Images.Media.getBitmap(getContentResolver(), originalUri);
                        privateIvId.setImageBitmap(bm);
                        drivingLicensePath = getRealImagePathFromURI(getContentResolver(), originalUri);


                    } catch (Exception e) {
                        throw new RuntimeException("相册异常");

                    }
                    break;


            }
        }


    }

    public static String getRealImagePathFromURI(ContentResolver contentResolver,
                                                 Uri contentURI) {
        Cursor cursor = contentResolver.query(contentURI, null, null, null,
                null);
        if (cursor == null)
            return contentURI.getPath();
        else {
            cursor.moveToFirst();
            int idx = cursor
                    .getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            try {
                return cursor.getString(idx);
            } catch (Exception exception) {
                return null;
            }
        }
    }


}
